import axios from 'axios'
// const KEY_TOKEN = 'token'


class HttpRequest {
  constructor(baseUrl) {
    this.baseUrl = baseUrl;
    this.queue = {}
  }

  getInsideConfig() {
    const config = {
      // baseURL: this.baseUrl,
      headers: {
        // token: localStorage.getItem(KEY_TOKEN), // 认证信息
        // local: localStorage.getItem('local') // 浏览器语言
      }
    }
    // console.log(config, '-----config')
    return config
  }

  destroy(url) {
    delete this.queue[url]
    if (!Object.keys(this.queue).length) {
      // Spin.hide()
    }
  }

  interceptors(instance, url) {
    // 请求拦截
    instance.interceptors.request.use(config => {
      // 添加全局的loading...
      if (!Object.keys(this.queue).length) {
        // Spin.show() // 不建议开启，因为界面不友好
      }
      this.queue[url] = true
      return config
    }, error => {
      return Promise.reject(error)
    })
    // 响应拦截
    instance.interceptors.response.use(res => {
      this.destroy(url)
      const {data, status} = res
      return {data, status}
    }, error => {
      this.destroy(url)
      let errorInfo = error.response
      if (!errorInfo) {
        const {request: {statusText, status}, config} = JSON.parse(JSON.stringify(error))
        errorInfo = {
          statusText,
          status,
          request: {responseURL: config.url}
        }
      }
      // addErrorLog(errorInfo)
      return Promise.reject(error)
    })
  }

  request(options) {
    let urlArr = options.url.split('/')
    options.url = urlArr.slice(1, urlArr.length).join('/')
    if (import.meta.env.DEV) {
      options.url = this.baseUrl + `/${urlArr[0]}` + "/" + options.url
    } else {
      options.url = this.baseUrl + `/${urlArr[0]}` + "/" + options.url
    }
    let config = this.getInsideConfig()
    const instance = axios.create()
    options = Object.assign(config, options)
    this.interceptors(instance, options.url)
    return instance(options).then(response => response)
  }
}

export default HttpRequest
